package com.bbt.dormassistant.service.impl;

import com.bbt.dormassistant.entity.UserInformation;
import com.bbt.dormassistant.service.LoginService;
import com.bbt.dormassistant.service.UserInformationService;
import com.bbt.dormassistant.util.WXLoginUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserInformationService userInformationService;


    /**
     *
     * @param code 临时码
     * @return String(userId)
     */
    @Override
    public String WXLogin(String code, String encryptedData, String iv) {

        Map<String, Object> userInfo = (Map<String, Object>) WXLoginUtil.getOpenId(code,encryptedData,iv).get("userInfo");

        /*判断数据库中是否存在该用户
            不存在：添加该用户 并返回用户信息
            存在：返回用户信息
        */
        String userId= (String) userInfo.get("openId");
        if(userInformationService.queryUserInformationById(userId) == null){
            UserInformation userInformation=new UserInformation();
            userInformation.setUserId(userId);
            userInformation.setNickname((String) userInfo.get("nickName"));
            userInformation.setAvatarUrl((String) userInfo.get("avatarUrl"));
            userInformationService.addUserInformation(userInformation);
        }

        return userId;
    }

}
